package com.ubhave.powertracker;

import java.util.Calendar;
import java.util.Date;

import com.ubhave.powertracker.R;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;

//import android.app.Activity;
import android.support.v4.app.FragmentActivity;
//import android.app.DialogFragment;
import android.support.v4.app.DialogFragment;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
 
public class PowerTrackerPreferences extends PreferenceActivity implements LoginDialogListener{
        
		String usr;
		String intervention;
		SharedPreferences settings;
		SharedPreferences.Editor editor;
		LifeGuideConnector lgc;
		PageSensorLogger psl;
		PageLogger pl;
		
		PowerTrackerSharedPreferenceChangeListener prefChangeListener;
		
		boolean interventionAdmin;
		Preference appPref;
	
		@Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                
                //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                //StrictMode.setThreadPolicy(policy);
                
                settings =PreferenceManager.getDefaultSharedPreferences(getBaseContext());
                editor = settings.edit();
                lgc = new LifeGuideConnector(settings);
                usr = settings.getString("LifeGuideUser", "");
        		intervention = settings.getString("LifeGuideInterventionId", "");
        		interventionAdmin = settings.getBoolean("interventionAdmin", false);
        		      
                addPreferencesFromResource(R.xml.preferences);
                
                prefChangeListener = new PowerTrackerSharedPreferenceChangeListener();
                settings.registerOnSharedPreferenceChangeListener(prefChangeListener);
                //Log.i("POWeR Tracker Special: ", "Prefs: PrefListen On");
        		                
                appPref=findPreference("ApplicationPreferences");
                
                //final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
                //final SharedPreferences.Editor editor = preferences.edit();
                
                if(settings.getBoolean("SensorsOn", false))    		
        			psl = new PageSensorLogger(this);
                pl=new PageLogger(this);
                
                class AsyncLog extends AsyncTask{

        			@Override
        			protected Object doInBackground(Object... params) {
        				        				
        				/*editor.putString("usageLog", settings.getString("usageLog", "")+params[0].getClass().getSimpleName()+" "+new Date()+", ");
        				editor.commit();
        				if(!usr.equals("")&&!intervention.equals("")){
        					lgc.postVar(intervention, usr, "user", "appUsageLog", settings.getString("usageLog", ""),settings.getString("authkey",""));
        				}
        				else
        					Log.i("POWeR Tracker: ", "Log fail usr: "+usr+" int: "+intervention);*/
        				
        				try{
        					pl.makeLog();
        				
        					if(settings.getBoolean("SensorsOn", false)){
        						psl.makeLog();
                			}
        				
        					//Log.i("POWeR Tracker Special: ","Logged for Preferences");
        					
        					String interventionAdminValue = lgc.getVar(intervention, usr, "user", "intAdmin",settings.getString("authkey",""));
    						editor.putBoolean("interventionAdmin",new Boolean(interventionAdminValue).booleanValue());
    						editor.commit();
    						
        				} catch (PowerTrackerInvalidAuthKeyException e) {
        					invalidKey();
        				}
        				
        				return null;
        			}
        			
        			protected void onPostExecute(Object result) {
        				setAppPrefLink();
        		    }
                };
                new AsyncLog().execute(this);
                
                //Set up a custom preference for cancelling alarms
                Preference alarmCancelPref = (Preference) findPreference("cancelAlarmPref");
                alarmCancelPref.setOnPreferenceClickListener(
                		new OnPreferenceClickListener() {
 
                			public boolean onPreferenceClick(Preference preference) {
                				Toast.makeText(getBaseContext(),
                						"Reminders Cancelled",
                						Toast.LENGTH_LONG).show();
                                                
                				AlarmManager alarmManager = (AlarmManager)PowerTrackerApplication.getContext().getSystemService(PowerTrackerApplication.getContext().ALARM_SERVICE);
                				
                				Intent myIntent = new Intent(PowerTrackerApplication.getContext() , DailyUpdateReminderNotification.class);     
                				PendingIntent pendingIntent = PendingIntent.getService(PowerTrackerApplication.getContext(), 0, myIntent, 0);
                                alarmManager.cancel(pendingIntent);
                                
                                myIntent = new Intent(PowerTrackerApplication.getContext() , DailyViewReminderNotification.class);     
                				pendingIntent = PendingIntent.getService(PowerTrackerApplication.getContext(), 0, myIntent, 0);
                                alarmManager.cancel(pendingIntent);
                                
                                myIntent = new Intent(PowerTrackerApplication.getContext() , DailyQuestionnaireReminderNotification.class);     
                				pendingIntent = PendingIntent.getService(PowerTrackerApplication.getContext(), 0, myIntent, 0);
                                alarmManager.cancel(pendingIntent);
                                                
                				return true;
                			}
 
                		}
                );
                
                //Set up a custom preference for logging in
                Preference loginPref = (Preference) findPreference("powerLogin");
                loginPref.setOnPreferenceClickListener(
                		new OnPreferenceClickListener() {
                			public boolean onPreferenceClick(Preference preference) {
                				//DialogFragment dialog = new LoginDialog();
                		        //dialog.show(getFragmentManager(), "LoginDialog");
                				
                				//This is a horrendous hack ... but at the moment unfortunately neacessary. PreferenceActivity is NOT supported by the support Library. As Authentication requires DialogFragments which are not supported before API11 this forces us to either not support API10 and lower or make bad login dialogs for preferences appears through another activity. I am doing there here using the main activity, removing authkey will make the activity load a first time login.
                				editor.remove("authkey");
                				editor.remove("LifeGuideUser");
                				editor.commit();
                				goHome();
                				return true;
                			}
                		}
				);
                                
                 
		
                if(settings.getString("interventionMode", "").equals("2")){
                	Preference questionnaireAlarm = findPreference("questionnaireNotificationTime");
                	getPreferenceScreen().removePreference(questionnaireAlarm);
                }
                
                setAppPrefLink();
		}
		
		@Override
	    protected void onPause() {
	        super.onPause();
	        settings.unregisterOnSharedPreferenceChangeListener(prefChangeListener);
	        //Log.i("POWeR Tracker Special: ", "Pref: PrefListen Off");
	        if(psl!=null)
	        	psl.stopLocationSensing();
	    }
	    
	    @Override
	    protected void onResume() {
	        super.onResume();
	        if(psl!=null)
	        	psl.resumeLocationSensing();
	    }
	    
	    @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	        	
	    	switch (item.getItemId()) {
	            case android.R.id.home:
	                // app icon in action bar clicked; go home
	                goHome();
	                return true;
	            case R.id.home:
	                // app icon in options clicked; go home
	            	goHome();
	                return true;
	            default:
	                return super.onOptionsItemSelected(item);
	        }
	    }
	    
	    @Override
	    public boolean onCreateOptionsMenu(Menu menu) {
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.menu.o_menu, menu);
	        return true;
	    }
	    
	    public void goHome(){
	    	//finish();
	    	Intent intent = new Intent(this, PowerTrackerActivity.class);
	        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        //startActivity(intent);
	        startActivityForResult(intent,0);
	    }
	    
	    public void setAppPrefLink(){
	    	interventionAdmin = settings.getBoolean("interventionAdmin", false);
	    	if(!interventionAdmin){
	    		if(appPref!=null)
	    			getPreferenceScreen().removePreference(appPref);
	    	}
	    	else{
	    		appPref.setOrder(0);
	    		getPreferenceScreen().addPreference(appPref);
	    	}
	    }
	    
	    public void invalidKey(){
			//DialogFragment dialog = new LoginDialog();
			Bundle errorBundle = new Bundle();
		    errorBundle.putString("error", "Your Authentication Key is invalid, expired, or is missing. Please Log In.");
		    //dialog.setArguments(errorBundle);
		    //dialog.show(this.getFragmentManager(), "LoginDialog");
		    
		    //This is a horrendous hack ... but at the moment unfortunately neacessary. PreferenceActivity is NOT supported by the support Library. As Authentication requires DialogFragments which are not supported before API11 this forces us to either not support API10 and lower or make bad login dialogs for preferences appears through another activity. I am doing there here using the main activity, removing authkey will make the activity load a first time login.
			goHome();
		}
	    
	  	@Override
		public void onLoginDialogPositiveClick() {
			// TODO Auto-generated method stub
	  		//Log.i("POWeR Tracker Special: ","Clicked OK");
	  		finish();
	  		startActivity(getIntent());
		}


		@Override
		public void onLoginDialogNegativeClick() {
			// TODO Auto-generated method stub
			//Log.i("POWeR Tracker Special: ","Clicked Cancel");
			goHome();
		}
}
